package com.jianjun.framework.manager.factory;


import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.jfinal.aop.Invocation;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.render.JsonRender;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.enums.BusinessStatus;
import com.jianjun.common.enums.OperatorType;
import com.jianjun.common.util.LogUtils;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.common.util.ip.AddressUtils;
import com.jianjun.common.util.ip.IpUtils;
import com.jianjun.framework.security.LoginUser;
import com.jianjun.framework.web.interceptor.CORSGlobalInterceptor;
import com.jianjun.project.common.model.SysLogininfor;
import com.jianjun.project.common.model.SysMenu;
import com.jianjun.project.common.model.SysOperLog;
import com.jianjun.project.common.model.SysUser;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author source
 */
@Slf4j
public class AsyncFactory {
    private static final SysMenu dao = new SysMenu().dao();

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
                                             final Object... args) {
        UserAgent userAgent = UserAgentUtil.parse(CORSGlobalInterceptor.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIp(ip);
                String s = LogUtils.getBlock(ip) +
                        address +
                        LogUtils.getBlock(username) +
                        LogUtils.getBlock(status) +
                        LogUtils.getBlock(message);
                // 打印信息到日志
                log.info(s, args);
                // 获取客户端操作系统
                String os = userAgent.getOs().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                logininfor.setLoginTime(new Date());
                // 日志状态
                if (StrUtil.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                logininfor.save();
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @return 任务task
     */
    public static TimerTask recordOper(final Invocation inv, final TimeInterval timer, final Exception e) {
        SysOperLog operLog = new SysOperLog();
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // *========数据库日志=========*//
        operLog.setOperUrl(StrUtil.sub(CORSGlobalInterceptor.getRequest().getRequestURI(), 0, 255));
        if (loginUser != null) {
            operLog.setOperName(SecurityUtils.getUsername());
            SysUser currentUser = loginUser.getUser();
            if (Objects.nonNull(currentUser) && Objects.nonNull(currentUser.getDept())) {
                operLog.setDeptName(currentUser.getDept().getDeptName());
            }
        }
        // 请求的地址
        String ip = IpUtils.getIpAddr();
        operLog.setOperIp(ip);
        // 设置请求方式
        operLog.setRequestMethod(CORSGlobalInterceptor.getRequest().getMethod());
        // 设置方法名称
        String className = inv.getController().getClass().getName();
        String methodName = inv.getMethodName();
        operLog.setMethod(className + "." + methodName + "()");
        // 设置消耗时间
        operLog.setCostTime(timer.interval());
        // 设置操作时间
        operLog.setOperTime(new Date());
        //操作类别
        operLog.setOperatorType(OperatorType.MANAGE.ordinal());
        operLog.setOperParam(StrUtil.sub(StrUtil.isEmpty(inv.getController().getRawData()) ? inv.getController().getKv().toJson() : inv.getController().getRawData(), 0, 2000));
        if (inv.getController().getRender() != null && inv.getController().getRender() instanceof JsonRender) {
            operLog.setJsonResult(StrUtil.sub(((JsonRender) inv.getController().getRender()).getJsonText(), 0, 2000));
        }

        return new TimerTask() {
            @Override
            public void run() {
                String[] splits = operLog.getOperUrl().split("/");
                if (splits.length > 2) {
                    List<SysMenu> menuList = dao.findByCache("querySysMenu", "allMenu", Db.getSql("querySysMenu"));
                    for (SysMenu item : menuList) {
                        if (item.getPath().equals(splits[2])) {
                            operLog.setTitle(item.getMenuName());
                            break;
                        }
                    }
                }
                operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
                if (e != null) {
                    operLog.setStatus(BusinessStatus.FAIL.ordinal());
                    operLog.setErrorMsg(StrUtil.sub(e.getMessage(), 0, 2000));
                }
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIp(operLog.getOperIp()));
                operLog.save();
            }
        };
    }
}
